<template>
    <div class="cont">
        <nav-bar title="关键词回复" rightImg="https://h5.dhcc.wang/newprogram/wxRobot/nav_refresh_black.png" :bgStyle="bgStyle"
            text-color="#333333" :rotate.sync="reload" @leftClick="back" @rightClick="refresh" />
        <div class="p-b-70">
            <div class="flex align-center justify-between m-lr-12 radius8 m-t-15 m-b-20 p-10 bg-white box-shadow-new">
                <div class="title van-ellipsis text-bold">
                    一键开启官方关键词
                </div>
                <div class="flex align-center">
                    <div class="m-r-10 color-primary font-12 flex justify-center align-center"
                        @click="openPage('/keywordPreview', { type: 1 })">关键词预览
                    </div>
                    <van-switch size="20" v-model="isKeywordReplyPublic" :active-color="config.mac_assist_color"
                        @change="changePublicState()" />
                </div>
            </div>
            <div class="m-lr-12 radius8 m-b-20 box-shadow-new" v-for="(item, index) in list" :key="item.id">
                <div class="comment">
                    <img src="https://img.alicdn.com/imgextra/i4/O1CN011kIz9H1xwiPaHnhNs_!!6000000006508-2-tps-78-54.png" class="summary">
                    <van-tag v-for="(opt, i) in item.keywordList" :key="i" type="primary"
                        class="m-r-10 m-b-10 p-tb-3 p-lr-8 " closeable @close="delKeyword(opt, item, index)">
                        <div class="tag van-ellipsis">{{ opt.title }}</div>
                    </van-tag>
                    <van-icon class="open-close" v-if="item.total > 10" color="#dddddd" size="18" style="top:5px" name="arrow-down"
                        @click="addKeywordList(item, 2, index)" />
                    <div class="flex align-center justify-end m-t-20">
                        <img class="m-r-10 radius4" width="24"
                            :src="item.small_head_img_url || 'https://h5.dhcc.wang/images/default_avatar.png'" alt="">
                        <div class="title van-ellipsis font-12">
                            {{ item.nick_name }}
                        </div>
                    </div>
                </div>
                <div class="flex justify-between van-hairline--top p-tb-12 p-lr-12">
                    <div class="flex">
                        <div class="flex align-center" @click="addKeywordList(item, 1, index)"><van-icon class="m-r-5"
                                name="setting-o" />添加关键词

                        </div>
                        <div class="flex align-center m-l-20" @click="addKeywordList(item, 2, index)">

                            <van-icon class="m-r-5" size="18" name="eye-o" />查看全部


                        </div>
                    </div>

                    <div class="flex align-center">
                        {{ item.is_keyword_reply ? '已开启' : "未启用" }}
                        <van-switch class="m-l-10" v-model="item.is_keyword_reply" size="20"
                            :active-color="config.mac_assist_color" @change="changeState(item)" />
                    </div>
                </div>
            </div>
            <div class="pad-lr pad-b bg-gray">
                <van-skeleton :loading="isLoadingSkeleton" avatar :row="4" v-for="i in 6" :key="i" />
            </div>
        </div>

        <noData v-if="list && list.length == 0" text="暂无激活的群" />
        <div class="footer  flex justify-between m-lr-30">
            <van-button class="p-lr-20" round type="warning"
                @click="openPage('/keywordPreview', { type: 2 })">
                <div class="flex align-center">
                    <div class="icon flex align-center m-r-5">T</div>
                    关键词管理
                </div>
            </van-button>
            <van-button class="p-lr-20" icon="plus" round type="primary"
                @click="addKeyWord()">新建关键词</van-button>
        </div>
        <!-- 添加、编辑关键词 -->
        <keywordAdd v-if="addShow" :popup-visible="addShow" :list="list" @close="keywordClose" />
        <keywordAddList v-if="addListShow" :popup-visible="addListShow" :username="username" :type="keywordData.viewType"
            @close="keywordListClose" @submits="submits" />
    </div>
</template>

<script>
import { Switch, Icon, Dialog, Tag, Popup, Button } from 'vant'
import keywordAdd from '@/components/keywordAdd.vue'
import keywordAddList from '@/components/keywordAddList.vue'
export default {
    components: {
        keywordAdd,
        keywordAddList,
        [Switch.name]: Switch,
        [Icon.name]: Icon,
        [Dialog.name]: Dialog,
        [Tag.name]: Tag,
        [Popup.name]: Popup,
        [Button.name]: Button
    },
    data () {
        return {
            config: {},
            main_color: '',
            assist_color: '',
            bgStyle: '#fff',
            bgOfficial: '#fff',
            reload: false,
            nodata: false,
            list: [],
            isLoadingSkeleton: false,
            addShow: false,
            isKeywordReplyPublic: false,
            addListShow: false,
            username: '',
            keywordData: {}
        }
    },
    mounted () {
        this.config = this.$DB.get('robotCfg')
        this.bgOfficial = `linear-gradient(90deg, ${this.config.mac_main_color} 0%, ${this.config.mac_assist_color} 100%)`
        if (this.config.device_info && this.config.device_info.expires_time && this.config.device_info.expires_time > 0) {
            let nowTime = new Date().getTime()
            let surDay = (this.config.device_info.expires_time * 1000) - nowTime
            this.day = parseInt(surDay / (60 * 60 * 24 * 1000))
        }
        this.setHeader()
        this.init()
        this.getList(true)
    },
    methods: {
        init () {
            this.$api.keywordConfig().then(res => {
                this.isKeywordReplyPublic = res.data.is_keyword_reply_public
            })
        },
        getList () {
            this.$api.getListGroup({ group_type: 2, status: 1, page: 1, pagesize: 30 }, true).then(async res => {
                console.log(res)
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.list = res.data.list
                res.data.list.forEach(async (item, index) => {
                    // item.keywordList = []
                    item.isOpen = false
                    item.total = 0
                    let ret = await this.getKeywordList(item)
                    this.$forceUpdate()
                    this.$set(res.data.list, index, ret)
                })
            }).finally(() => {
                setTimeout(() => {
                    this.reload = false
                }, 300)
            })
        },
        async getKeywordList (item) {
            const {
                data: {
                    list,
                    total
                }
            } = await this.$api.keywordList({
                username: item.user_name,
                page: 1
            })
            this.$set(item, 'keywordList', list)
            this.$set(item, 'total', total)
            return item
        },
        refresh () {
            this.reload = true
            this.getList(true)
        },
        openPage (url, item = {}) {
            this.$router.push({
                path: url,
                query: item
            })
        },
        back () {
            this.$router.go(-1)
        },
        setHeader () {
            this.$common.setHeader({
                native_headershow: 0,
                topstyle: 'topcolor',
                native_top_words_color: '#ffffff',
                str_link_color: '#ffffff',
                end_link_color: '#ffffff'
            })
        },
        // 添加关键词
        addKeyWord () {
            this.addShow = true
        },
        keywordClose (data = false) {
            this.addShow = false
            if (data) {
                this.getList()
            }
        },
        // 删除关键词
        delKeyword (opt, item, index) {
            Dialog.confirm({
                title: '温馨提示',
                message: '确定要移除该关键词回复吗？'
            })
                .then(() => {
                    let arr = opt.user_name.split(',')
                    let i = arr.findIndex(t => t == item.user_name)
                    arr.splice(i, 1)
                    this.$api.keywordAddOrUpdate({
                        id: opt.id,
                        username: arr.join(','),
                        title: opt.title,
                        reply: opt.reply,
                        reply_type: opt.reply_type,
                        status: 1
                    }).then(async res => {
                        if (res.code != 1) {
                            return this.$toast(res.msg)
                        }
                        this.$toast('删除成功')
                        let ret = await this.getKeywordList(item)
                        this.$forceUpdate()
                        this.$set(this.list, index, ret)
                    })
                })
                .catch(() => {
                    // on cancel
                })
        },
        // 开启/关闭关键词回复
        changeState (item) {
            if (item.keywordList && item.keywordList.length == 0 && item.is_keyword_reply) {
                item.is_keyword_reply = false
                return this.$toast('请先新建关键词才能开启')
            }
            this.$api.keywordReplyStatus({
                username: item.user_name,
                status: item.is_keyword_reply ? 1 : 0
            }).then(res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.$toast('设置成功')
            })
        },
        // 官方关键词开关
        changePublicState () {
            this.$api.keywordReplyPublicStatus({ status: this.isKeywordReplyPublic ? 1 : 0 }).then(res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.$toast('设置成功')
            })
        },
        addKeywordList (item, type, index) {
            this.username = item.user_name
            this.keywordData = item
            this.keywordData.index = index
            this.keywordData.viewType = type
            this.addListShow = true
        },
        async submits () {
            let ret = await this.getKeywordList(this.keywordData)
            this.$set(this.list, this.keywordData.index, ret)
            this.$forceUpdate()
        },
        keywordListClose () {
            this.addListShow = false
        }

    }
}
</script>
<style lang="less" scoped>
.cont {
    font-size: 14px;
    padding-top: 46px;

    .btn {
        color: #672e12;
        border-radius: 4px;
        font-size: 12px;
    }

    .title {
        max-width: calc(100.0vw - 200px);
    }

    .add-left {
        flex: 0 0 70px;
        font-size: 14px;
    }



    .footer {
        position: fixed;
        bottom: 20px;
        left: 0;
        right: 0;
    }

    .icon {
        padding: 0 3px;
        border: 1px solid #fff;
        color: #fff;
        border-radius: 2px;
        font-weight: 500;
    }

    .tag {
        max-width: calc(33vw - 57px);
    }
    .comment {
        background-image: linear-gradient(101deg,rgba(216,228,255,.5) 11%,rgba(225,216,255,0) 88%);
        border-radius: 6px 6px 0 0;
        padding: 20px 15px 15px;
        position: relative;
        color: #0d2357;
        .summary {
            left: 2px;
            position: absolute;
            top: -4px;
            height: 18px;
            -o-object-fit: contain;
            object-fit: contain;
        }
    }
}
</style>